﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace Common.Extend
{
    public static class ExEnum
    {
        /// <summary>
        /// 转换成TextValue对象集合
        /// </summary>
        /// <param name="em"></param>
        /// <param name="t">typeOf(enum)</param>
        /// <returns></returns>
        public static IList<KeyValuePair<string, string>> ExConvertToList(this Enum em)
        {
            IList<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
            Array arr = Enum.GetValues(em.GetType());
            foreach (Enum e in arr)
            {
                list.Add(new KeyValuePair<string, string>(e.ToString(),((int)Enum.Parse(em.GetType(), e.ToString())).ToString()));
            }
            return list;
        }
        /// <summary>
        /// 扩展方法，获得枚举的Description
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute，是否使用枚举名代替，默认是使用</param>
        /// <returns>枚举的Description</returns>
        public static string ExGetDescription(this Enum value, bool nameInstead = true)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name == null)
            {
                return null;
            }
            System.Reflection.FieldInfo field = type.GetField(name);
            DescriptionAttribute attribute = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute == null && nameInstead)
            {
                return name;
            }
            if (attribute != null)
            {
                return attribute.Description;
            }
            return null;
        }
    }
}
